﻿/// <reference path="uicontrol.ts" />

module UI {

    export class ListBox extends UIControl {

        public type: string = 'ListBox';

        public items: Array<ListBoxItem> = [];

        public selectedIndex: number = -1;

        public onClick: InputEvent = null;

        public onEnter: InputEvent = null;

        public onExit: InputEvent = null;

        public onSelectionChanged: SelectionChangedEvent = null;

        constructor(details: any = undefined) {
            super();
            setupControl(this, details);
            this.handleClick = this.handleClickInternal;
        }

        render(context: CanvasRenderingContext2D) {

            var c = this.computed;

            // Outline
            context.lineWidth = 2;
            context.fillStyle = '#eee';
            context.fillRect(c.left, c.top, c.width, c.height);
            context.strokeStyle = UI.COLOR_TEXT_DARK;
            context.strokeRect(c.left, c.top, c.width, c.height);

            // Items
            context.textBaseline = 'top';
            context.textAlign = 'left';
            context.font = UI.FONT_NORMAL;
            context.fillStyle = UI.COLOR_TEXT_DARK;
            var y = 8;
            for (var itemSelector in this.items) {
                context.fillText(this.items[itemSelector].text, c.left + 8, c.top + y);
                y += 20;
            }

            // Draw selected item
            if (this.selectedIndex > -1) {
                context.fillStyle = UI.COLOR_DOWN_FILL;
                context.fillRect(c.left + 4, c.top + 8 + this.selectedIndex * 20, c.width - 8, 20);
                context.fillStyle = UI.COLOR_TEXT_LIGHT;
                context.fillText(this.items[this.selectedIndex].text, c.left + 8, c.top + 8 + this.selectedIndex * 20);
            }
        }

        handleClickInternal(sender: UIControl, e: InputArgs) {
            var c = this.computed;
            this.selectedIndex = Math.max(0, Math.min(this.items.length - 1, Math.floor((c.mouse.y - 8) / 20)));
            if (this.onSelectionChanged !== undefined && this.onSelectionChanged !== null) {
                var args = SelectionChangedArgs.create(this.selectedIndex, this.items[this.selectedIndex]);
                this.onSelectionChanged(this, args);
            }
        }

    }

}
 